<template>
  <div class="statistics">
    <!-- 顶部筛选区域 -->
    <el-card class="filter-card">
      <el-form :inline="true" :model="filterForm" class="filter-form">
        <el-form-item label="时间范围">
          <el-select v-model="filterForm.timeRange" placeholder="选择时间范围">
            <el-option label="今天" value="today" />
            <el-option label="本周" value="week" />
            <el-option label="本月" value="month" />
            <el-option label="自定义" value="custom" />
          </el-select>
        </el-form-item>
        <el-form-item v-if="filterForm.timeRange === 'custom'">
          <el-date-picker
            v-model="filterForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleFilter">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
          <el-button type="success" @click="handleExport">导出数据</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 统计卡片 -->
    <el-row :gutter="20" class="statistics-cards">
      <el-col :span="6">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>总阅读量</span>
              <el-tag type="success">+12.5%</el-tag>
            </div>
          </template>
          <div class="card-value">{{ statistics.totalReads }}</div>
          <div class="card-compare">较昨日 {{ statistics.readsCompare }}</div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>粉丝数量</span>
              <el-tag type="success">+8.2%</el-tag>
            </div>
          </template>
          <div class="card-value">{{ statistics.totalFans }}</div>
          <div class="card-compare">较昨日 {{ statistics.fansCompare }}</div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>互动总量</span>
              <el-tag type="warning">+5.3%</el-tag>
            </div>
          </template>
          <div class="card-value">{{ statistics.totalInteractions }}</div>
          <div class="card-compare">较昨日 {{ statistics.interactionsCompare }}</div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>文章数量</span>
              <el-tag type="info">+2.1%</el-tag>
            </div>
          </template>
          <div class="card-value">{{ statistics.totalArticles }}</div>
          <div class="card-compare">较昨日 {{ statistics.articlesCompare }}</div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 图表区域 -->
    <el-row :gutter="20" class="chart-row">
      <!-- 阅读趋势 -->
      <el-col :span="12">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>阅读趋势</span>
              <el-tag size="small">近30天</el-tag>
            </div>
          </template>
          <div ref="readTrendChart" class="chart-container"></div>
        </el-card>
      </el-col>

      <!-- 粉丝增长 -->
      <el-col :span="12">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>粉丝增长</span>
              <el-tag size="small">近30天</el-tag>
            </div>
          </template>
          <div ref="fansTrendChart" class="chart-container"></div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" class="chart-row">
      <!-- 互动统计 -->
      <el-col :span="12">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>互动统计</span>
              <el-tag size="small">本月</el-tag>
            </div>
          </template>
          <div ref="interactionChart" class="chart-container"></div>
        </el-card>
      </el-col>

      <!-- 内容分布 -->
      <el-col :span="12">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>内容分布</span>
              <el-tag size="small">本月</el-tag>
            </div>
          </template>
          <div ref="contentDistributionChart" class="chart-container"></div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 活跃度热力图 -->
    <el-row class="chart-row">
      <el-col :span="24">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>活跃度分析</span>
              <el-tag size="small">本周</el-tag>
            </div>
          </template>
          <div ref="activityHeatmap" class="heatmap-container"></div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import * as echarts from 'echarts'
import type { EChartsOption } from 'echarts'

// 筛选表单
const filterForm = reactive({
  timeRange: 'month',
  dateRange: [] as string[]
})

// 统计数据
const statistics = reactive({
  totalReads: 0,
  readsCompare: 0,
  totalFans: 0,
  fansCompare: 0,
  totalInteractions: 0,
  interactionsCompare: 0,
  totalArticles: 0,
  articlesCompare: 0
})

// 图表实例
const readTrendChart = ref<HTMLElement>()
const fansTrendChart = ref<HTMLElement>()
const interactionChart = ref<HTMLElement>()
const contentDistributionChart = ref<HTMLElement>()
const activityHeatmap = ref<HTMLElement>()

// 生成日期数组
const generateDates = (days: number) => {
  const dates = [] as string[]
  const now = new Date()
  for (let i = days - 1; i >= 0; i--) {
    const date = new Date(now)
    date.setDate(date.getDate() - i)
    dates.push(date.toLocaleDateString())
  }
  return dates
}

// 生成随机数据
const generateRandomData = (min: number, max: number, count: number) => {
  return Array.from({ length: count }, () => 
    Math.floor(Math.random() * (max - min + 1)) + min
  )
}

// 初始化统计数据
const initStatistics = () => {
  statistics.totalReads = Math.floor(Math.random() * 10000) + 5000
  statistics.readsCompare = Math.floor(Math.random() * 1000)
  statistics.totalFans = Math.floor(Math.random() * 1000) + 500
  statistics.fansCompare = Math.floor(Math.random() * 100)
  statistics.totalInteractions = Math.floor(Math.random() * 5000) + 2000
  statistics.interactionsCompare = Math.floor(Math.random() * 500)
  statistics.totalArticles = Math.floor(Math.random() * 100) + 50
  statistics.articlesCompare = Math.floor(Math.random() * 10)
}

// 初始化阅读趋势图
const initReadTrendChart = () => {
  if (!readTrendChart.value) return
  
  const chart = echarts.init(readTrendChart.value)
  const dates = generateDates(30)
  const data = generateRandomData(100, 500, 30)

  const option: EChartsOption = {
    tooltip: {
      trigger: 'axis'
    },
    xAxis: {
      type: 'category',
      data: dates,
      axisLabel: {
        rotate: 45
      }
    },
    yAxis: {
      type: 'value'
    },
    series: [{
      data,
      type: 'line',
      smooth: true,
      areaStyle: {
        opacity: 0.3
      }
    }]
  }

  chart.setOption(option)
}

// 初始化粉丝增长图
const initFansTrendChart = () => {
  if (!fansTrendChart.value) return
  
  const chart = echarts.init(fansTrendChart.value)
  const dates = generateDates(30)
  const data = generateRandomData(10, 50, 30)

  const option: EChartsOption = {
    tooltip: {
      trigger: 'axis'
    },
    xAxis: {
      type: 'category',
      data: dates,
      axisLabel: {
        rotate: 45
      }
    },
    yAxis: {
      type: 'value'
    },
    series: [{
      data,
      type: 'line',
      smooth: true,
      areaStyle: {
        opacity: 0.3
      }
    }]
  }

  chart.setOption(option)
}

// 初始化互动统计图
const initInteractionChart = () => {
  if (!interactionChart.value) return
  
  const chart = echarts.init(interactionChart.value)
  const data = [
    { value: Math.floor(Math.random() * 1000) + 500, name: '点赞' },
    { value: Math.floor(Math.random() * 800) + 300, name: '评论' },
    { value: Math.floor(Math.random() * 600) + 200, name: '收藏' },
    { value: Math.floor(Math.random() * 400) + 100, name: '分享' }
  ]

  const option: EChartsOption = {
    tooltip: {
      trigger: 'item',
      formatter: '{b}: {c} ({d}%)'
    },
    series: [{
      type: 'pie',
      radius: ['40%', '70%'],
      data,
      emphasis: {
        itemStyle: {
          shadowBlur: 10,
          shadowOffsetX: 0,
          shadowColor: 'rgba(0, 0, 0, 0.5)'
        }
      }
    }]
  }

  chart.setOption(option)
}

// 初始化内容分布图
const initContentDistributionChart = () => {
  if (!contentDistributionChart.value) return
  
  const chart = echarts.init(contentDistributionChart.value)
  const data = [
    { value: Math.floor(Math.random() * 50) + 20, name: '技术文章' },
    { value: Math.floor(Math.random() * 40) + 15, name: '生活随笔' },
    { value: Math.floor(Math.random() * 30) + 10, name: '学习笔记' },
    { value: Math.floor(Math.random() * 20) + 5, name: '项目经验' },
    { value: Math.floor(Math.random() * 15) + 5, name: '其他' }
  ]

  const option: EChartsOption = {
    tooltip: {
      trigger: 'item',
      formatter: '{b}: {c} ({d}%)'
    },
    series: [{
      type: 'pie',
      radius: ['40%', '70%'],
      data,
      emphasis: {
        itemStyle: {
          shadowBlur: 10,
          shadowOffsetX: 0,
          shadowColor: 'rgba(0, 0, 0, 0.5)'
        }
      }
    }]
  }

  chart.setOption(option)
}

// 初始化活跃度热力图
const initActivityHeatmap = () => {
  if (!activityHeatmap.value) return
  
  const chart = echarts.init(activityHeatmap.value)
  const hours = Array.from({ length: 24 }, (_, i) => `${i}:00`)
  const days = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']
  
  const data = [] as number[][]
  for (let i = 0; i < 7; i++) {
    for (let j = 0; j < 24; j++) {
      data.push([j, i, Math.floor(Math.random() * 100)])
    }
  }

  const option: EChartsOption = {
    tooltip: {
      position: 'top'
    },
    grid: {
      height: '70%',
      top: '10%'
    },
    xAxis: {
      type: 'category',
      data: hours,
      splitArea: {
        show: true
      }
    },
    yAxis: {
      type: 'category',
      data: days,
      splitArea: {
        show: true
      }
    },
    visualMap: {
      min: 0,
      max: 100,
      calculable: true,
      orient: 'horizontal',
      left: 'center',
      bottom: '5%'
    },
    series: [{
      name: '活跃度',
      type: 'heatmap',
      data,
      label: {
        show: true
      },
      emphasis: {
        itemStyle: {
          shadowBlur: 10,
          shadowColor: 'rgba(0, 0, 0, 0.5)'
        }
      }
    }]
  }

  chart.setOption(option)
}

// 处理筛选
const handleFilter = () => {
  // 重新加载数据
  initStatistics()
  initCharts()
  ElMessage.success('数据已更新')
}

// 重置筛选
const handleReset = () => {
  filterForm.timeRange = 'month'
  filterForm.dateRange = []
  handleFilter()
}

// 导出数据
const handleExport = () => {
  // 模拟数据导出
  const exportData = {
    statistics,
    timeRange: filterForm.timeRange,
    dateRange: filterForm.dateRange,
    exportTime: new Date().toLocaleString()
  }
  
  const blob = new Blob([JSON.stringify(exportData, null, 2)], { type: 'application/json' })
  const url = URL.createObjectURL(blob)
  const link = document.createElement('a')
  link.href = url
  link.download = `statistics_${new Date().getTime()}.json`
  link.click()
  URL.revokeObjectURL(url)
  
  ElMessage.success('数据导出成功')
}

// 初始化所有图表
const initCharts = () => {
  nextTick(() => {
    initReadTrendChart()
    initFansTrendChart()
    initInteractionChart()
    initContentDistributionChart()
    initActivityHeatmap()
  })
}

// 监听窗口大小变化
const handleResize = () => {
  const charts = [
    readTrendChart.value && echarts.getInstanceByDom(readTrendChart.value),
    fansTrendChart.value && echarts.getInstanceByDom(fansTrendChart.value),
    interactionChart.value && echarts.getInstanceByDom(interactionChart.value),
    contentDistributionChart.value && echarts.getInstanceByDom(contentDistributionChart.value),
    activityHeatmap.value && echarts.getInstanceByDom(activityHeatmap.value)
  ].filter(Boolean)

  charts.forEach(chart => chart?.resize())
}

// 初始化
onMounted(() => {
  initStatistics()
  initCharts()
  window.addEventListener('resize', handleResize)
})
</script>

<style scoped>
.statistics {
  padding: 20px;
}

.filter-card {
  margin-bottom: 20px;
}

.statistics-cards {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-value {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
  margin: 10px 0;
}

.card-compare {
  font-size: 14px;
  color: #909399;
}

.chart-row {
  margin-bottom: 20px;
}

.chart-container {
  height: 300px;
}

.heatmap-container {
  height: 400px;
}
</style>
